package com.nandi.deviceinstall.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.TimePickerView
import com.nandi.deviceinstall.R
import com.nandi.deviceinstall.base.BaseMvpActivity
import com.nandi.deviceinstall.bean.*
import com.nandi.deviceinstall.common.Constant
import com.nandi.deviceinstall.contract.BindRecordContract
import com.nandi.deviceinstall.presenter.BindRecordPresenter
import com.nandi.deviceinstall.ui.adapter.RecordsAdapter
import com.nandi.deviceinstall.util.SharedTool
import com.nandi.deviceinstall.weight.InitDataListener
import kotlinx.android.synthetic.main.activity_record.*
import kotlinx.android.synthetic.main.toolbar_back_include.*
import java.text.SimpleDateFormat
import java.util.*
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.jaygoo.selector.MultiSelectPopWindow
import com.nandi.deviceinstall.util.CustomToast
import java.io.Serializable


class RecordActivity : BaseMvpActivity<BindRecordPresenter>(), BindRecordContract.View {


    private val listDeviceType = arrayOf("地裂缝", "墙裂缝", "地面倾斜", "智能报警器", "雨量计", "泥位计")
    private var current = 1
    private var pageSize = 10
    private var listCitys: MutableList<CityBean.DataBean> = mutableListOf()
    private var listTowns: MutableList<TownBean.DataBean> = mutableListOf()
    private var listFactorys: MutableList<DeviceFacBean.DataBean> = mutableListOf()
    private var listMonitorNums: MutableList<ListMonitorNumBean.DataBean> = mutableListOf()
    private var citys = mutableListOf<String>()
    private var towns = mutableListOf<String>()
    private var disastersName = mutableListOf<String>()
    private var disastersNu = mutableListOf<String>()
    private var monitorNums = mutableListOf<String>()
    private var deviceFacs = mutableListOf<String>()
    //private val monitorNuUuidBuffer = StringBuffer()
    private lateinit var cityAdapter: ArrayAdapter<String>
    private lateinit var townAdapter: ArrayAdapter<String>
    private lateinit var disasterNameAdapter: ArrayAdapter<String>
    private lateinit var disasterNuAdapter: ArrayAdapter<String>
    private lateinit var deviceFacsAdapter: ArrayAdapter<String>
    private lateinit var typesAdapter: ArrayAdapter<String>
    private lateinit var monitorNumAdapter: ArrayAdapter<String>
    private var startDate = Calendar.getInstance()
    //private var endDate = Calendar.getInstance()
    private lateinit var timePicker: TimePickerView
    private var isStartTime = false
    private var sort = 2
    private var isSearch = false
    private var token = ""
    private var isAddress = false
    private var isSelectCity = false
    private var isSelectTown = false

    lateinit var mAdapter: RecordsAdapter

    override val layoutId: Int
        get() = R.layout.activity_record

    @SuppressLint("SimpleDateFormat")
    override fun initView() {
        mPresenter = BindRecordPresenter()
        mPresenter.attachView(this)

        token = SharedTool.get(context, Constant.TOKEN, "") as String
        tv_title_toolbar.text = "记录"
        ll_right.visibility =View.GONE
        //startDate.set(2000, 0, 1, 0, 0, 0)

        val allShow = booleanArrayOf(true, true, true, true, true, true)

        timePicker = TimePickerBuilder(context, OnTimeSelectListener { date, _ ->
            if (isStartTime) {
                startTime.text = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)
            } else {
                endTime.text = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)
            }
        })
                .setType(allShow)
                .setCancelText("取消")
                .setSubmitText("确认")
                .setContentTextSize(18)
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择日期")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setDate(startDate)
                .setLabel("年", "月", "日", "时", "分", "秒")
                .isDialog(false)
                .build()

        data_show.layoutManager = LinearLayoutManager(context)
        mAdapter = RecordsAdapter(R.layout.item_record)
        data_show.adapter = mAdapter
        mAdapter.setEnableLoadMore(true)
        mAdapter.setEmptyView(R.layout.empty_item,data_show)
        mAdapter.setOnLoadMoreListener({
            if (isSearch) {
                var city = ""
                if (district.getmPosition() != -1) {
                    city = listCitys[district.getmPosition()].areaCode!!
                }
                var town = ""
                if (township.getmPosition() != -1) {
                    town = listTowns[township.getmPosition()].areaCode!!
                }
                loadMore(city, sort, town, disasterName.text.toString(), disasterNum.text.toString(), monitorNum.text.toString(),
                        startTime.text.toString(), endTime.text.toString(), 1, devType.getmPosition(),
                        devNum.text.toString(), devFac.text.toString())
            } else {
                loadMore("", sort, "", "", "", "", "", "",
                        1, -1, "", "")
            }
        }, data_show)

        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItem(position) as BindRecordBean.DataBean.RecordsBean
            val intent = Intent(context, RecordInfoActivity::class.java)
            intent.putExtra("item", item as Serializable)
            startActivity(intent)
        }

        mAdapter.setOnItemChildClickListener { _, _, position ->
            MaterialDialog.Builder(this)
                    .title("提示")
                    .content("确认删除?")
                    .positiveText("确认")
                    .negativeText("取消")
                    .onPositive { _, _ -> mPresenter.requestDeleteBindRecord(token, mAdapter.getItem(position)!!.id) }
                    .show()
        }

        srlTemplate.setOnRefreshListener {
            refresh()
        }

        refresh()
        initListener()
    }

    override fun handlerDeleteBind(result: BindDeleteBean) {
        refresh()
    }

    private fun initListener() {
        iv_back_toolbar.setOnClickListener { finish() }

        address.setOnClickListener {
            isAddress = true
            mPresenter.requestListCity(token, "")
        }

        time.setOnClickListener {
            if (sort == 1) {
                sort = 2
            } else if (sort == 2) {
                sort = 1
            }
            current = 1
            if (isSearch) {
                var city = ""
                if (district.getmPosition() != -1) {
                    city = listCitys[district.getmPosition()].areaCode!!
                }
                var town = ""
                if (township.getmPosition() != -1) {
                    town = listTowns[township.getmPosition()].areaCode!!
                }
                getData(city, sort, town, disasterName.text.toString(), disasterNum.text.toString(), monitorNum.text.toString(),
                        startTime.text.toString(), endTime.text.toString(), 1, devType.getmPosition(),
                        devNum.text.toString(), devFac.text.toString())
            } else {
                getData("", sort, "", "", "", "",
                        "", "", 1, -1, "", "")
            }
        }
        //策划菜单
        more.setOnClickListener {
            if (!drawer.isDrawerOpen(root)) {
                drawer.openDrawer(root)
            }
        }
        cancel.setOnClickListener {
            if (drawer.isDrawerOpen(root)) {
                drawer.closeDrawer(root)
                isSearch = false
            }
        }

        submit.setOnClickListener {
            isSearch = true
            current = 1
            var city = ""
            if (district.getmPosition() != -1) {
                city = listCitys[district.getmPosition()].areaCode!!
            }
            var town = ""
            if (township.getmPosition() != -1) {
                town = listTowns[township.getmPosition()].areaCode!!
            }
            getData(city, sort, town, disasterName.text.toString(), disasterNum.text.toString(), monitorNum.text.toString(),
                    startTime.text.toString(), endTime.text.toString(), 1, devType.getmPosition(),
                    devNum.text.toString(), devFac.text.toString())
        }

        typesAdapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, listDeviceType)

        devType.setAdapter(typesAdapter)
        devType.setInitDataListener { devType.showPopWindow() }

        devFac.setInitDataListener { mPresenter.requestListDevFactory(token, "") }
        devFac.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (!devFac.isMySelected) {
                    if (p0.toString().isEmpty()) {
                        return
                    }
                    mPresenter.requestListDevFactory(token, p0.toString())
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        district.setInitDataListener { mPresenter.requestListCity(token, "") }
        district.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (district.isTextChanged) {
                    isSelectCity = true
                    township.text = ""
                    disasterName.setText("")
                    disasterNum.text = ""
                    monitorNum.text = ""
                    isSelectCity = false
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        township.setInitDataListener {
            if (district.text.isNotEmpty()) {
                val id = listCitys[district.getmPosition()].id
                mPresenter.requestListTown(token, id)
            } else {
                showLongToast("请先选择区县!")
            }
        }
        township.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (township.isTextChanged) {
                    isSelectTown = true
                    disasterName.setText("")
                    disasterNum.text = ""
                    monitorNum.text = ""
                    isSelectTown = false
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        disasterName.setInitDataListener {
            if (township.text.isNotEmpty()) {
                //isDisasterName = true
                val areaCode = listTowns[township.getmPosition()].areaCode
                mPresenter.requestListDisaster(token, 1, 1000000, areaCode!!)
                /*disasterNum.setText("")*/
            } else {
                showLongToast("请先选择乡镇!")
            }
        }
        disasterName.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (disasterName.isTextChanged) {
                    disasterNum.text = ""
                    monitorNum.text = ""
                }

                if (!disasterName.isMySelected && !isSelectCity && !isSelectTown) {
                    if (district.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择区县")
                        return
                    }
                    if (township.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择乡镇")
                        return
                    }
                    if (p0.toString().isEmpty()) {
                        return
                    }
                    val areaCode = listTowns[township.getmPosition()].areaCode
                    mPresenter.requestDisName(token, p0.toString(), areaCode!!)
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

        })

        disasterNum.setInitDataListener {
            if (township.text.isNotEmpty()) {
                val areaCode = listTowns[township.getmPosition()].areaCode
                mPresenter.requestDisNum(token, disasterName.text.toString(), areaCode!!)
            } else {
                showLongToast("请先选择灾害点名称!")
            }
        }

        disasterNum.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (disasterNum.isTextChanged) {
                    monitorNum.text = ""
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })

        monitorNum.setInitDataListener {
            if (disasterNum.text.isNotEmpty()) {
                mPresenter.requestListMonitorNum(token, disasterNum.text.toString())
            } else {
                showLongToast("请选择灾害点编号!")
            }
        }

        startTime.setOnClickListener {
            isStartTime = true
            timePicker.show()
        }

        endTime.setOnClickListener {
            isStartTime = false
            timePicker.show()
        }
    }

    private fun loadMore(areaCode: String, sort: Int, townCode: String, disasterName: String,
                         disNo: String, monitorNo: String, startTime: String, endTime: String, isAppAdd: Int,
                         devType: Int, devName: String, devFactory: String) {
        current++
        getData(areaCode, sort, townCode, disasterName, disNo, monitorNo, startTime, endTime, isAppAdd,
                devType, devName, devFactory)
    }

    private fun refresh() {
        //mAdapter.data.clear()
        current = 1
        isSearch = false
        getData("", 2, "", "", "", "",
                "", "", 1, -1, "", "")
    }

    private fun getData(areaCode: String, sort: Int, townCode: String, disasterName: String, disNo: String,
                monitorNo: String, startTime: String, endTime: String, isAppAdd: Int, devType: Int,
                devName: String, devFactory: String) {
        mPresenter.requestListRecord(token, current, pageSize,
                areaCode, sort, townCode, disasterName, disNo,
                monitorNo, startTime, endTime, isAppAdd, devType, devName, devFactory)
    }

    private fun setData(data: MutableList<BindRecordBean.DataBean.RecordsBean>) {

        val size = data.size
        mAdapter.addData(data)
        if (size < pageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
    }


    override fun showLoading() {
    }

    override fun hideLoading() {
    }

    override fun onError(msg: String, code: Int) {
        CustomToast.showToast(context,msg)
    }

    override fun handlerListRecordResult(result: BindRecordBean) {
        srlTemplate.isRefreshing = false
        mAdapter.data.clear()
        setData(result.data?.records!!)
        if (drawer.isDrawerOpen(root)) {
            drawer.closeDrawer(root)
        }
    }

    override fun handlerListCityResult(result: CityBean) {
        listCitys.clear()
        listCitys.addAll(result.data!!)
        //var citys = mutableListOf<String>()
        citys.clear()
        result.data?.forEach {
            citys.add(it.areaName!!)
        }
        if (isAddress) {
            citys.add(0, "全部")
            val pvOptions = OptionsPickerBuilder(this@RecordActivity
                    , OnOptionsSelectListener { options1, _, _, _ ->
                //返回的分别是三个级别的选中位置
                address.text = citys[options1]
                if (options1 == 0) {
                    getData("", sort, "", "", "", "",
                            "", "", 1, -1, "", "")
                } else {
                    getData(listCitys[options1 - 1].areaCode!!, sort, "", "", "", "",
                            "", "", 1, -1, "", "")
                }
            }).build<Any>()
            pvOptions.setPicker(citys as List<String>)
            pvOptions.show()
            isAddress = false
        } else {
            cityAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, citys)
            district.setAdapter(cityAdapter)
            district.showPopWindow()
        }

    }

    override fun handlerListTownResult(result: TownBean) {
        listTowns.clear()
        listTowns.addAll(result.data!!)
        //var towns = mutableListOf<String>()
        towns.clear()
        result.data?.forEach {
            towns.add(it.areaName!!)
        }
        townAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, towns)
        township.setAdapter(townAdapter)
        township.showPopWindow()

    }

    override fun handlerListDisasterResult(result: DisasterBean) {
        //var disastersName = mutableListOf<String>()
        disastersName.clear()
        result.data?.forEach {
            disastersName.add(it.disasterName!!)
        }
        disasterNameAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersName)
        disasterName.setAdapter(disasterNameAdapter)
        disasterName.showPopWindow()
    }

    override fun handlerDisNum(result: DisNumBean) {
        if (result.data!!.isNotEmpty()) {
            //var disastersNu = mutableListOf<String>()
            disastersNu.clear()
            result.data?.forEach {
                disastersNu.add(it)
            }
            disasterNuAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersNu)
            disasterNum.setAdapter(disasterNuAdapter)
            disasterNum.showPopWindow()
        } else {
            showShortToast("没有相关灾害点编号!")
        }
    }

    override fun handlerDevFactory(result: DeviceFacBean) {
        if (result.data!!.isNotEmpty()) {
            listFactorys.clear()
            listFactorys.addAll(result.data!!)
            //val deviceFacs = mutableListOf<String>()
            deviceFacs.clear()
            result.data?.forEach {
                deviceFacs.add(it.factory!!)
            }
            deviceFacsAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, deviceFacs)
            devFac.setAdapter(deviceFacsAdapter)
            devFac.showPopWindow()
        }
    }

    override fun handlerMonitorNum(result: ListMonitorNumBean) {

        if (result.data != null) {
            listMonitorNums.clear()
            listMonitorNums.addAll(result.data!!)
            //val monitorNums = mutableListOf<String>()
            monitorNums.clear()
            result.data?.forEach {
                monitorNums.add(it.monitorNo!!)
            }
            if (devType.text.toString() == "智能报警器") {
                //isChoice = true
                MultiSelectPopWindow.Builder(this)
                        .setNameArray(monitorNums as ArrayList<String>)
                        .setConfirmListener { indexList, selectedList ->
                            val monitorNuBuffer = StringBuffer()
                            /*for (i in indexList) {
                                monitorNuUuidBuffer.append(result.data!![i].uuid)
                                monitorNuUuidBuffer.append(",")
                            }*/
                            selectedList.forEach {
                                monitorNuBuffer.append(it)
                                monitorNuBuffer.append(",")
                            }
                            monitorNum.text = monitorNuBuffer.substring(0, monitorNuBuffer.length - 1)
                            monitorNum.setTextColor(Color.BLACK)
                            monitorNum.textSize = 18f
                        }
                        .setCancel("取消")
                        .setConfirm("完成")
                        .setTitle("编号列表")
                        .build()
                        .show(mBottom)
            } else {
                monitorNumAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, monitorNums)
                monitorNum.setAdapter(monitorNumAdapter)
                monitorNum.showPopWindow()
            }
        } else {
            showLongToast("此灾害点没有监测点编号!")
        }
    }

    override fun handlerDisNameResult(result: DisNameBean) {
        if (result.data!!.records!!.isNotEmpty()) {
            //var disastersName = mutableListOf<String>()
            disastersName.clear()
            result.data?.records?.forEach {
                disastersName.add(it.disasterName!!)
            }
            disasterNameAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersName)
            disasterName.setAdapter(disasterNameAdapter)
            disasterName.showPopWindow()
        } /*else {
            showShortToast("没有相关灾害点!")
        }*/
    }

}
